
import fs from 'fs';

let five = new Map();
let seven = new Map();

export class example extends plugin {
  constructor() {
    super({
      name: '古诗接龙[poems]',
      dsc: '古诗接龙',
      /** https://oicqjs.github.io/oicq/#events */
      event: 'message',
      priority: 99999,
      rule: [
        {
          /** 匹配五言和七言 */
          reg: '^([\u4e00-\u9fa5]{5}|[\u4e00-\u9fa5]{7})，([\u4e00-\u9fa5]{5}|[\u4e00-\u9fa5]{7})。?$',
          /** 执行方法 */
          fnc: 'jielong'
        }
      ]
    })
  }

  async init() {
    fs.readdir('./plugins/poems-plugin/resources/five-poems', (err, files) => {
      if (err) {
        console.error('读取目录失败:', err);
        return;
      }
      files.forEach(file => {
        let poems = JSON.parse(fs.readFileSync(`./plugins/poems-plugin/resources/five-poems/${file}`, 'utf-8'));
        let keys = Object.keys(poems);
        keys.forEach(key => {
          five.set(key, file);
        });
      });
      logger.mark('五言诗加载完成');
    });

    fs.readdir('./plugins/poems-plugin/resources/seven-poems', (err, files) => {
      if (err) {
        console.error('读取目录失败:', err);
        return;
      }
      files.forEach(file => {
        let poems = JSON.parse(fs.readFileSync(`./plugins/poems-plugin/resources/seven-poems/${file}`, 'utf-8'));
        let keys = Object.keys(poems);
        keys.forEach(key => {
          seven.set(key, file);
        });
      });
      logger.mark('七言诗加载完成');
    });
  }

  /** 古诗接龙 */
  async jielong(e) {
    let messages = e.msg.trim().replace(/[？。！]/g, '').split('，');
    if (messages[0].length === 5) {
      let res = this.getPoem(messages[1][4], 5);
      return res ? e.reply(res) : res;
    }
    if (messages[0].length === 7) {
      let res = this.getPoem(messages[1][6], 7);
      return res ? e.reply(res) : res;
    }
  }

  getPoem(firstChar, length) {
    let poemsMap = length === 5 ? five : seven;
    if (poemsMap.has(firstChar)) {
      let path = `./plugins/poems-plugin/resources/${length === 5 ? 'five-poems' : 'seven-poems'}/${poemsMap.get(firstChar)}`;
      let poems = JSON.parse(fs.readFileSync(path, 'utf-8'))[firstChar];
      return poems[Math.floor(Math.random() * poems.length)];
    }
    return null;
  }
}
